<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <div class="tree-area">
      <div
        class="tree-item"
        v-for="(item, index) in menus"
        :key="index"
        v-if="item.status == '0'"
      >
        <div class="title">
          <div class="title-left">
            <span>{{ item.label }}</span>
            <el-checkbox
              :ref="'father-checkbox' + index"
              :disabled="
                !item.children ||
                item.children.length == 0 ||
                disabledFalge ||
                item.disabled
              "
              :indeterminate="item.indeterminate"
              v-model="item.checked"
              @change="handlerChangefather(item)"
            ></el-checkbox>
          </div>
          <i
            @click.stop="handlerChangeshowChildren(item)"
            :class="[
              'title-right',
              item.showChildren ? 'el-icon-arrow-down' : 'el-icon-arrow-up',
            ]"
          ></i>
        </div>
        <div
          class="children-area"
          v-if="item.children && item.children.length > 0 && item.showChildren"
        >
          <div
            class="children-item"
            v-for="(tig, tindex) in item.children"
            :key="tindex"
            v-if="tig.status == '0'"
          >
            <el-checkbox
              :ref="'children-checkbox' + tindex"
              :disabled="disabledFalge || tig.disabled"
              v-model="tig.checked"
              :indeterminate="tig.indeterminate"
              @change="handlerChangechildren(item, tig)"
            >
              {{ tig.label }}
            </el-checkbox>
            <i
              v-if="tig.children && tig.children.length"
              @click.stop="handlerChangeshowChildren2(item, tig)"
              :class="[
                'children-right',
                tig.showChildren ? 'el-icon-arrow-down' : 'el-icon-arrow-up',
              ]"
            ></i>
            <div class="three-area" v-if="tig.showChildren">
              <div
                class="three-item"
                v-for="(pig, pindex) in tig.children"
                :key="pindex"
                v-if="pig.status == '0'"
              >
                <el-checkbox
                  :ref="'three-checkbox' + pindex"
                  :disabled="disabledFalge"
                  v-model="pig.checked"
                  :indeterminate="pig.indeterminate"
                  @change="handlerChangechildren2(item, tig, pig)"
                >
                  {{ pig.label }}
                </el-checkbox>
                <div class="four-area">
                  <div
                    class="four-item"
                    v-for="(sig, sindex) in pig.children"
                    :key="sindex"
                    v-if="sig.status == '0'"
                  >
                    <el-checkbox
                      :ref="'four-checkbox' + sindex"
                      :disabled="disabledFalge"
                      v-model="sig.checked"
                      @change="handlerChangechildren3(item, tig, pig, sig)"
                    >
                      {{ sig.label }}
                    </el-checkbox>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="button-area">
      <el-button
        @click="handlerSubmit"
        size="small"
        type="primary"
        v-if="!disabledFalge"
      >
        保存
      </el-button>
      <el-button @click="goBack" size="small">取消</el-button>
    </div>
  </lb-layout>
</template>

<script>
import {
  requestwebList,
  menuRole,
  requestscreenList,
  screenRole,
} from "@/api/auth/index.js";
export default {
  components: {},
  data() {
    return {
      disabledFalge: true,
      roleId: null,
      menus: [],
      checked: false,
      checkedArr: [],
      menuIds: [],
    };
  },
  created() {},
  mounted() {
    this.judgeWhoandType();
  },
  methods: {
    judgeWhoandType() {
      let query = this.$route.query;
      this.roleId = query.roleId;
      let falge = query?.disabled ?? "1";
      switch (falge) {
        case "0":
          this.disabledFalge = false;
          break;
        case "1":
          this.disabledFalge = true;
          break;
      }
      setTimeout(() => {
        if (this.$route.name == "authorSet") {
          this.getwebList(); // web
        } else if (this.$route.name == "authorSet2") {
          this.getscreenlist(); // 大屏
        }
      }, 100);
    },
    getwebList() {
      requestwebList(this.roleId)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let menus = res?.menus ?? [];
          this.checkedArr = res?.checkedKeys ?? [];
          this.dealMenu(menus);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    getscreenlist() {
      requestscreenList(this.roleId)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let menusArr = res?.menus ?? [];
          this.checkedArr = res?.checkedKeys ?? [];
          this.dealMenu(menusArr);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    dealMenu(menus) {
      this.menus = menus;
      this.recursionDealmenu(this.menus);
      this.showMychildren();
      this.$nextTick(() => {
        this.checkedArr.map((val) => {
          this.recursionDealcheck(val, this.menus);
        });
        this.recursionDealindeterminate(this.menus);
        this.$nextTick(() => {
          this.menus = [...this.menus];
        });
      });
    },
    // 打上收缩标签
    showMychildren() {
      this.menus.map((item) => {
        item.showChildren = true;
        if (item.children && item.children.length > 0) {
          item.children.map((tig) => {
            tig.showChildren = true;
          });
        }
      });
    },
    // 递归处理menu checked 重置为false
    recursionDealmenu(arr) {
      arr.map((item) => {
        item.checked = false;
        if (item.children && item.children.length > 0) {
          this.recursionDealmenu(item.children);
        }
      });
    },
    // 递归处理menu选中
    recursionDealcheck(val, arr) {
      arr.map((item) => {
        if (item.id == val) {
          item.checked = true;
        }
        // 能效一览默认选中且不可取消选择
        // 生产环境能效一览ID：2444 测试环境能效一览ID：2444
        if (item.id == 2444) {
          item.checked = true;
          item.disabled = true;
        }
        // 管理中心也不可取消选择
        // 生产环境管理中心ID：2285 测试环境管理中心ID：2285
        if (item.id == 2285) {
          item.disabled = true;
        }
        if (item.children && item.children.length > 0) {
          this.recursionDealcheck(val, item.children);
        }
      });
    },
    // 递归处理menu不确认状态
    recursionDealindeterminate(arr) {
      arr.map((item) => {
        if (item.children && item.children.length > 0) {
          let num = 0;
          item.children.map((tig) => {
            if (tig.checked == true) {
              num++;
            }
          });
          if (num != 0 && num < item.children.length) {
            item.indeterminate = true;
          } else if (num == item.children.length) {
            item.indeterminate = false;
          } else if (num == 0) {
            item.indeterminate = false;
          }
          this.recursionDealindeterminate(item.children);
        } else {
          item.indeterminate = false;
        }
      });
    },
    /* ........................选择操作........................ */
    // 处理 子集的checked indeterminate
    fatherchildrenFalseorTrue(arr, falge) {
      arr.map((item) => {
        item.checked = falge;
        item.indeterminate = false;
        if (item.children && item.children.length > 0) {
          this.fatherchildrenFalseorTrue(item.children, falge);
        }
      });
    },
    // 最外层选择（第一层）
    handlerChangefather(target) {
      this.menus.map((item) => {
        if (item.id == target.id) {
          if (target.indeterminate) {
            item.checked = false;
            item.indeterminate = false;
            if (item.children && item.children.length > 0) {
              // 子集全部取消勾选
              this.fatherchildrenFalseorTrue(item.children, false);
            }
          } else {
            item.checked = target.checked;
            if (item.children && item.children.length > 0) {
              this.fatherchildrenFalseorTrue(item.children, target.checked);
            }
          }
        }
      });
      this.$nextTick(() => {
        this.menus = [...this.menus];
      });
    },
    // 点击赋值对应menus的自己和自己的子集（第四层）
    handlerChangechildren3(target, target2, target3, target4) {
      this.menus.map((item) => {
        if (item.id == target.id) {
          item.children.map((tig) => {
            if (tig.id == target2.id) {
              tig.children.map((pig) => {
                if (pig.id == target3.id) {
                  pig.children.map((sig) => {
                    if (sig.id == target4.id) {
                      sig.checked = target4.checked;
                      sig.indeterminate = false;
                      // 第四层为最后一层
                    }
                  });
                }
              });
            }
          });
        }
      });
      this.$nextTick(() => {
        this.childrenCheck(this.menus);
        this.$nextTick(() => {
          this.childrenCheck(this.menus);
          this.$nextTick(() => {
            this.childrenCheck(this.menus);
            this.$nextTick(() => {
              this.menus = [...this.menus];
            });
          });
        });
      });
    },
    // 点击赋值对应menus的自己和自己的子集（第三层）
    handlerChangechildren2(target, target2, target3) {
      this.menus.map((item) => {
        if (item.id == target.id) {
          item.children.map((tig) => {
            if (tig.id == target2.id) {
              tig.children.map((pig) => {
                if (pig.id == target3.id) {
                  pig.checked = target3.checked;
                  pig.indeterminate = false;
                  if (pig.children && pig.children.length > 0) {
                    this.fatherchildrenFalseorTrue(
                      pig.children,
                      target3.checked
                    );
                  }
                }
              });
            }
          });
        }
      });
      this.$nextTick(() => {
        this.childrenCheck(this.menus);
        this.$nextTick(() => {
          this.childrenCheck(this.menus);
          this.$nextTick(() => {
            this.menus = [...this.menus];
          });
        });
      });
    },
    // 点击赋值对应menus的自己和自己的子集（第二层）
    handlerChangechildren(target, target2) {
      this.menus.map((item) => {
        if (item.id == target.id) {
          item.children.map((tig) => {
            if (tig.id == target2.id) {
              tig.checked = target2.checked;
              tig.indeterminate = false;
              if (tig.children && tig.children.length > 0) {
                this.fatherchildrenFalseorTrue(tig.children, target2.checked);
              }
            }
          });
        }
      });
      this.$nextTick(() => {
        this.childrenCheck(this.menus);
        this.$nextTick(() => {
          this.menus = [...this.menus];
        });
      });
    },
    // 子集遍历确认父级的状态 checked 和 indeterminate
    childrenCheck(arr) {
      arr.map((item) => {
        if (item.children && item.children.length > 0) {
          let num = 0;
          item.children.map((tig) => {
            if (tig.checked) {
              num++;
            }
          });
          if (num == item.children.length) {
            item.indeterminate = false;
            item.checked = true;
          } else if (num != 0 && num < item.children.length) {
            item.indeterminate = true;
            item.checked = true;
          } else if (num == 0) {
            item.indeterminate = false;
            item.checked = false;
          }
          this.childrenCheck(item.children);
          // 能效一览作为基础页面必选
          if (item.id == 2444) {
            item.checked = true;
            item.disabled = true;
          }
        }
      });
    },
    handlerSubmit() {
      let that = this;
      const text = "是否确认保存改角色？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.requestSave();
        })
        .catch(() => {
          that.$message({
            message: "取消保存",
          });
        });
    },
    // 请求保存
    requestSave() {
      let requestWay;
      if (this.$route.name == "authorSet") {
        requestWay = menuRole; // web
      } else if (this.$route.name == "authorSet2") {
        requestWay = screenRole; // 大屏
      }
      let query = {};
      query.roleId = this.roleId;
      this.menuIds = [];
      this.giveCheckedtomenuIds(this.menus);
      query.menuIds = this.menuIds;
      this.$nextTick(() => {
        requestWay(query)
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            this.$message.success("已保存!");
            this.goBack();
          })
          .catch(() => {
            // this.$message.error("系统错误,请联系管理员!");
          });
      });
    },
    giveCheckedtomenuIds(arr) {
      arr.map((item) => {
        if (item.checked) {
          this.menuIds.push(item.id);
          if (item.children && item.children.length > 0) {
            this.giveCheckedtomenuIds(item.children);
          }
        }
      });
    },
    goBack() {
      let activeMenu = this.$route.meta.activeMenu; // 激活的菜单也是返回的菜单
      this.$router.go(-1);
    },
    /* ........................开关操作........................ */
    handlerChangeshowChildren(target) {
      this.menus.map((item) => {
        if (target.id == item.id) {
          item.showChildren = !item.showChildren;
        }
      });
      this.$nextTick(() => {
        this.menus = [...this.menus];
      });
    },
    handlerChangeshowChildren2(target, target2) {
      this.menus.map((item) => {
        if (target.id == item.id) {
          item.children.map((tig) => {
            if (target2.id == tig.id) {
              tig.showChildren = !tig.showChildren;
            }
          });
        }
      });
      this.$nextTick(() => {
        this.menus = [...this.menus];
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox {
  height: 28px;
  width: auto;
  // max-width: 300px;
  display: flex;
  align-items: center;
  .el-checkbox__input {
    width: 28px;
    height: 28px;
    font-size: 24px;
    .el-checkbox__inner {
      width: 24px;
      height: 24px;

      &::after {
        height: 16px;
        left: 10px;
      }
      &::before {
        top: 10px;
      }
    }
  }
  .el-checkbox__label {
    line-height: 28px;
    font-size: 22px;
    font-weight: 400;
    color: rgb(0, 0, 0);
  }
}
.tree-area {
  width: 100%;
  display: flex;
  flex-direction: column;
  .tree-item {
    width: 100%;
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;
    .title {
      width: 100%;
      border-bottom: 2px solid #aaa8a8;
      padding: 10px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title-left {
        display: flex;
        align-items: center;
      }
      .title-right {
        width: 40px;
        height: 40px;
        text-align: center;
        cursor: pointer;
        font-size: 32px;
        font-weight: 400;
        font-style: normal;
        text-decoration: none;
        font-family: "Segoe UI";
        color: rgb(0, 0, 0);
      }

      .el-checkbox {
        margin: 10px 0 0 10px;
        ::v-deep .el-checkbox__input {
          .el-checkbox__inner {
            &::before {
              top: 10px;
            }
          }
        }
      }
      span {
        white-space: nowrap;
        text-align: left;
        font-size: 32px;
        font-weight: 400;
        font-style: normal;
        text-decoration: none;
        font-family: "Segoe UI";
        color: rgb(0, 0, 0);
      }
    }
    .children-area {
      margin-top: 20px;
      width: 100%;
      display: flex;
      flex-direction: column;
      .children-item {
        margin: 0 20px 20px 0;
        display: flex;
        flex-direction: column;
        position: relative;
        .el-checkbox {
          background-color: rgb(233, 233, 233);
          ::v-deep .el-checkbox__input {
            margin-left: 5px;
            margin-top: 4px;
          }
        }
        .children-right {
          position: absolute;
          right: 0px;
          width: 34px;
          height: 34px;
          text-align: center;
          cursor: pointer;
          font-size: 28px;
          font-weight: 400;
          font-style: normal;
          text-decoration: none;
          font-family: "Segoe UI";
          color: rgb(0, 0, 0);
        }
        .three-area {
          width: 100%;
          display: flex;
          flex-direction: column;
          .three-item {
            width: calc(100%-40px);
            margin-left: 40px;
            margin-bottom: 20px;
            display: flex;
            flex-direction: column;

            ::v-deep .el-checkbox {
              background-color: #ffff;
              margin: 10px 0 0 10px;
              .el-checkbox__input {
                width: 20px;
                height: 20px;
                .el-checkbox__inner {
                  width: 20px;
                  height: 20px;
                  &::after {
                    top: -2px;
                    left: 8px;
                  }
                  &::before {
                    top: 8px;
                  }
                }
              }
              .el-checkbox__label {
                line-height: 20px;
                font-size: 20px;
                font-weight: 400;
                color: rgb(0, 0, 0);
              }
            }

            .four-area {
              width: calc(100%-80px);
              margin-left: 40px;
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              .four-item {
                ::v-deep .el-checkbox {
                  margin: 10px 0 0 10px;
                  .el-checkbox__input {
                    width: 18px;
                    height: 18px;
                    .el-checkbox__inner {
                      width: 18px;
                      height: 18px;
                      &::after {
                        top: -2px;
                        left: 6px;
                      }
                    }
                  }
                  .el-checkbox__label {
                    line-height: 18px;
                    font-size: 18px;
                    font-weight: 400;
                    color: rgb(22, 22, 22);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
.button-area {
  position: sticky;
  bottom: 0px;
  width: 100%;
  padding-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
